import {
  getBaseUrl,
  requestUtil
} from '../../utils/requestUtil.js'


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    checked: false,
    telNumber: '',
    password: '',
    acceptOrder: 0,
    deliveryOrder: 0,
    finishOrder: 0,
    days: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      baseUrl: getBaseUrl()
    })
  },

  //获取用户输入的电话号码
  getTelNumber(e) {
    const telNumber = e.detail.value || ''
    this.setData({
      telNumber
    })
  },

  //获取用户输入的密码
  getPassword(e) {
    const password = e.detail.value || ''
    this.setData({
      password
    })
  },

  async login() {
    const {
      telNumber,
      password
    } = this.data
    if (!telNumber.trim() || !password.trim()) {
      wx.showToast({
        title: '用户名或密码为空！',
        icon: 'none'
      })
      return;
    }
    const res = await requestUtil({
      url: '/rider/user/login',
      data: {
        telNumber,
        password
      }
    })
    if (res.code == 0) {
      const {
        userInfo,
        token
      } = res
      wx.setStorageSync('userInfo', userInfo)
      wx.setStorageSync('token', token)
      wx.reLaunch({
        url: '/pages/my/index',
      })
    } else {
      wx.showToast({
        title: `${res.msg}`,
        icon: 'none'
      })
    }
  },

  async getNum(id) {
    const orderRes = await requestUtil({
      url: '/rider/order/getNum',
      data: {
        id
      }
    })
    const userRes = await requestUtil({
      url: '/rider/user/getNum',
      data: {
        id
      }
    })
    const {
      acceptOrder,
      deliveryOrder,
      finishOrder
    } = orderRes
    const {
      days
    } = userRes
    this.setData({
      acceptOrder,
      deliveryOrder,
      finishOrder,
      days
    })
  },

  goToRegister() {
    wx.navigateTo({
      url: '/pages/register/index',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const userInfo = wx.getStorageSync('userInfo')
    const token = wx.getStorageSync('token')
    if (!token) {
      this.setData({
        isLogin: false
      })
      return;
    }
    this.setData({
      isLogin: true,
      userInfo
    })
    this.getNum(userInfo.id)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})